package com.canbot.u05.activity.guide;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.bean.guide.*;
import com.canbot.u05.helper.DialogBuildHelper;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.socket.StringMsgBean;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.StatusBarUtil;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.view.MyMapTaskView;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.*;

/**
 * @author zmp
 * 导览模式添加任务界面
 */

public class GuideMapAddTaskActivity extends BaseActivityNoTitle {

        /**
         * 任务数据
         */
        public static final String TASK_DATA_KEY = "task_position";

        public static final String TASK_DATA = "taskInfo";

        private TextView titleTv;

        private MyMapTaskView mapTaskView;

        private MyTaskAdapter myTaskAdapter;


        /**
         * 当前任务包含的点数据
         */
        private List<MapPointInfo> mTaskPointInfos;

        /**
         * 当前任务数据
         */
        private MapTaskInfo mMapTaskInfo;

        private ToastTools toastTools;

        private int mTaskPosition;

        private Handler mHandler;

        private View ivOk;

        private View ivPb;

        private TextView tvLoad;

        /**
         * 请求码 --设置任务点
         */
        private static final int REQ_CODE_POINT = 1001;

        private RecyclerView recyclerView;

        private ItemTouchHelper itemTouchHelper;


        public static final int REQ_CODE_OVERLAY = 250;


        private DialogBuildHelper.TipBuilder hintDialog;

        private PopupWindow popupWindow;

        private int popPosition;

        private ViewGroup mainIv;

        protected static boolean isFirstAdd;

        private Button switchBt;

        private DialogBuildHelper.HintTipBuilder switchTip;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.guide_add_task_activity);
                EventBus.getDefault().register(this);
                toastTools = ToastTools.newInstance(this);
                mHandler = new Handler();
                //检查权限WindowManager 6.0权限检测
                if (!Settings.canDrawOverlays(this)) {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                        startActivityForResult(intent, REQ_CODE_OVERLAY);
                        return;
                }
                initViews();
        }

        private void initViews() {
                mainIv = (ViewGroup) findViewById(R.id.main_iv);
                titleTv = (TextView) findViewById(R.id.guide_base_title_tv);
                mapTaskView = (MyMapTaskView) findViewById(R.id.guide_task_mtv);
                recyclerView = (RecyclerView) findViewById(R.id.guide_add_task_rv);
                findViewById(R.id.guide_task_iv_save).setOnClickListener(onClickListener);
                findViewById(R.id.guide_task_iv_back).setOnClickListener(onClickListener);
                switchBt = (Button) findViewById(R.id.guide_switch_bt);
                switchBt.setOnClickListener(onClickListener);
                initData();
                initMapView();
                iniRecyclerView();
                if (mTaskPosition == -1) {
                        startOtherActivity(new Intent(this, GuideSplashActivity.class), false);
                }
        }

        private void iniRecyclerView() {
                recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                mTaskPointInfos = Collections.synchronizedList(mTaskPointInfos);
                myTaskAdapter = new MyTaskAdapter(this, mTaskPointInfos);
                recyclerView.setAdapter(myTaskAdapter);
                itemTouchHelper = new ItemTouchHelper(new MyCallBack(myTaskAdapter));
                itemTouchHelper.attachToRecyclerView(recyclerView);
        }

        private void initData() {
                mTaskPosition = getIntent().getIntExtra(TASK_DATA_KEY, -1);
                if (mTaskPosition == -1) {
                        mMapTaskInfo = new MapTaskInfo(GuideActivity.mMapInfo.get_id());
                        isFirstAdd = true;
                } else {
                        isFirstAdd = false;
                        mMapTaskInfo = JSONObject.parseObject(getIntent().getStringExtra(TASK_DATA), MapTaskInfo.class);
                }
                mTaskPointInfos = mMapTaskInfo.getMapPointInfos();
                if (mTaskPointInfos.size() > 0) {
                        Collections.sort(mTaskPointInfos, new Comparator<MapPointInfo>() {
                                @Override
                                public int compare(MapPointInfo lhs, MapPointInfo rhs) {
                                        return lhs.getIndex() - rhs.getIndex();
                                }
                        });
                }
                String taskName = mMapTaskInfo.getTaskName();
                if (TextUtils.isEmpty(taskName)) {
                        titleTv.setText(GuideActivity.mMapInfo.getMapName());
                } else {
                        titleTv.setText(taskName);
                }
                switchBt.setSelected(mMapTaskInfo.getClosest());
        }

        private void initMapView() {
                mapTaskView.setOnFinishListener(mOnStateListener);
                ArrayList<IMapPointBean> iMapPointBeen = new ArrayList<>();
                List<LocalPointsBean> localPoints = GuideActivity.mMapInfo.getLocalPoints();
                if (localPoints != null && localPoints.size() > 0) {
                        iMapPointBeen.addAll(localPoints);
                }
                //TODO 暂不显示人物点
                        /*List<PersonPointsBean> personPoints = GuideActivity.mMapInfo
                        .getPersonPoints();
                        if (personPoints != null && personPoints.size() > 0) {
                                iMapPointBeen.addAll(personPoints);
                        }*/
                //
                byte[] bytes = Base64.decode(GuideActivity.mMapInfo.getImagePng(), Base64.DEFAULT);
                mapTaskView.setMapPhoto(bytes);
                mapTaskView.setPoints(iMapPointBeen);
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (requestCode == REQ_CODE_OVERLAY) {
                        if (Settings.canDrawOverlays(this)) {
                                Log.e("onActivityResult", "resultCode:" + true);
                                initViews();
                        } else {
                                toastTools.showText(getString(R.string.permission_denied));
                                finish();
                        }
                }

                if (requestCode == REQ_CODE_POINT && resultCode == RESULT_OK) {
                        String pointInfo = data.getStringExtra("pointInfo");
                        MapPointInfo mapPointInfo = JSON.parseObject(pointInfo, MapPointInfo.class);
                        if (mPosition == -1) {
                                mTaskPointInfos.add(mapPointInfo);
                        } else {
                                mTaskPointInfos.remove(mPosition);
                                mTaskPointInfos.add(mPosition, mapPointInfo);
                        }
                        myTaskAdapter.notifyDataSetChanged();
                        isFirstAdd = false;
                }
        }

        /**
         * 消息发布者位置
         * ReceiveData
         * mHandler
         * case MsgType.MOBILE_PAD_MAP_TASK:
         *
         * @param bean
         */
        @Subscribe(threadMode = ThreadMode.MAIN)
        public void onMapEvent(StringMsgBean bean) {
                if (bean.getMsgType() == MsgType.MOBILE_PAD_MAP_TASK) {
                        String msgData = bean.getMsgData();
                        if (!TextUtils.isEmpty(msgData)) {
                                MapMsgBean mapMsgBean = new Gson().fromJson(msgData, MapMsgBean.class);
                                if (MapMsgBean.MOBILE_SAVE_TASK == mapMsgBean.getMsgType()) {
                                        if (mapMsgBean.isSuccess()) {
                                                handleSaveSuccess(mapMsgBean.getMsgData());
                                        } else {
                                                loadDialog.dismiss();
                                                toastTools.showText("保存失败！");
                                                MapVoiceAndEyes.playMapVoiceAndEyes(MapVoiceAndEyes.voiceEyesList.get(8));
                                        }
                                }
                        }
                }
        }

        /**
         * 任务保存成功
         *
         * @param taskID
         */
        private void handleSaveSuccess(String taskID) {
                List<MapTaskInfo> taskInfos = GuideActivity.mMapInfo.getMapTaskInfos();
                if (mTaskPosition != -1) {
                        taskInfos.remove(mTaskPosition);
                        taskInfos.add(mTaskPosition, mMapTaskInfo);
                } else {
                        mMapTaskInfo.set_id(Long.parseLong(taskID));
                        taskInfos.add(mMapTaskInfo);
                }
                MapVoiceAndEyes.playMapVoiceAndEyes(MapVoiceAndEyes.voiceEyesList.get(7));
                if (mTaskPosition == -1) {
                        loadDialog.dismiss();
                        startOtherActivity(new Intent(this, GuideSplashSaveActivity.class), true);
                        return;
                }
                ivPb.setVisibility(View.INVISIBLE);
                ivOk.setVisibility(View.VISIBLE);
                tvLoad.setText("保存成功！");
                mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                                loadDialog.dismiss();
                                finish();
                        }
                }, 1000);
        }

        public int mPosition;

        /**
         * 提示Dialog
         */
        private void showHintDialog() {
                showHintDialog(getString(R.string.task_exit_hint), new DialogBuildHelper.ITipClickListener() {
                        @Override
                        protected void sure() {
                                finish();
                        }
                });
        }

        private View.OnClickListener onClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                        switch (v.getId()) {
                                case R.id.guide_task_iv_back:
                                        if (mTaskPointInfos == null || mTaskPointInfos.size() == 0) {
                                                finish();
                                        } else {
                                                showHintDialog();
                                        }
                                        break;
                                //保存数据
                                case R.id.guide_task_iv_save:
                                        if (mTaskPointInfos.size() == 0) {
                                                toastTools.showText("亲,请先编辑任务点！");
                                                return;
                                        }
                                        if (mTaskPosition == -1) {
                                                showSaveTaskDialog();
                                        } else {
                                                showSaveTaskHintDialog();
                                        }
                                        break;
                                case R.id.guide_switch_bt:
                                        boolean selected = switchBt.isSelected();
                                        switchBt.setSelected(!selected);
                                        mMapTaskInfo.setClosest(!selected);
                                        showSwitchHintDialog(!selected);
                                        break;
                                default:


                        }

                }
        };

        private void showSwitchHintDialog(boolean b) {
                if (switchTip == null) {
                        switchTip = DialogBuildHelper.createHintTipDialog(this);
                        switchTip.setClickListener(null, true);
                }
                String str1 = "功能已开启,机器人将根据具体位置\n就近开启任务。";
                String str2 = "功能已关闭,机器人将完全按照设定\n路线执行任务。";
                switchTip.setContent(b ? str1 : str2, Gravity.CENTER);
                switchTip.show();
        }


        private void upTask2Server() {
                showLoadDialog();
                for (int i = 0; i < mTaskPointInfos.size(); i++) {
                        mTaskPointInfos.get(i).setIndex(i);
                }
                String toJson = JSON.toJSONString(mMapTaskInfo);
                sendMsg2Chest(toJson);
        }


        /**
         * 删除Dialog
         *
         * @param adapterPosition adapterPosition
         */
        private void showDeleteDialog(final int adapterPosition) {
                showHintDialog("是否删除此任务步骤?", new DialogBuildHelper.ITipClickListener() {
                        @Override
                        protected void sure() {
                                mTaskPointInfos.remove(adapterPosition);
                                myTaskAdapter.notifyItemRemoved(adapterPosition);
                        }
                });
        }

        private DialogBuildHelper.SetNameTipBuilder taskNameDialog;


        private void showSaveTaskHintDialog() {
                showHintDialog("是否将更改保存到此任务中?", new DialogBuildHelper.ITipClickListener() {
                        @Override
                        protected void sure() {
                                upTask2Server();
                        }
                });
        }

        private void showHintDialog(String content, DialogBuildHelper.ITipClickListener listener) {
                if (hintDialog == null) {
                        hintDialog = DialogBuildHelper.createDialogTip(this);
                }
                hintDialog.setContent(content, Gravity.CENTER).setClickListener(listener, true);
                hintDialog.show();
        }


        private void showSaveTaskDialog() {
                if (taskNameDialog == null) {
                        taskNameDialog = DialogBuildHelper.createDialogSetName(this).setClickListener(new DialogBuildHelper.ISetNameClickListener() {
                                @Override
                                protected void sure(String name, TextView tipTextView) {
                                        if (TextUtils.isEmpty(name)) {
                                                toastTools.showText("任务名不能为空哦!");
                                                tipTextView.setText("任务名不能为空哦!");
                                                return;
                                        }
                                        if (!name.matches("[\\u4E00-\\u9FA5A-Za-z0-9]+")) {
                                                toastTools.showText("任务名含有非法字符");
                                                tipTextView.setText("任务名含有非法字符!");
                                                return;
                                        }

                                        for (MapTaskInfo mTaskInfo : GuideActivity.mMapInfo.getMapTaskInfos()) {
                                                if (name.equals(mTaskInfo.getTaskName())) {
                                                        toastTools.showText("任务名已经存在");
                                                        tipTextView.setText("任务名已经存在");
                                                        return;
                                                }
                                        }
                                        mMapTaskInfo.setTaskName(name);
                                        taskNameDialog.dismiss();
                                        upTask2Server();
                                }
                        }, false).setTitle("任务命名");
                }
                taskNameDialog.show();
        }


        /**
         * 地图监听
         */
        MyMapTaskView.IOnStateListener mOnStateListener = new MyMapTaskView.IOnStateListener() {

                //地图点点击事件
                @Override
                public void onClick(IMapPointBean mapPointerBean) {
                        MapPointInfo taskPointInfo = new MapPointInfo(mMapTaskInfo.get_id(), mapPointerBean.getPointName());
                        mPosition = -1;
                        Intent intent = new Intent(GuideMapAddTaskActivity.this, GuideSetPointerActivity.class);
                        intent.putExtra("pointInfo", JSON.toJSONString(taskPointInfo));
                        if (isFirstAdd) {
                                MapVoiceAndEyes.playMapVoiceAndEyes(MapVoiceAndEyes.voiceEyesList.get(3));
                        }
                        startForResultActivity(intent, REQ_CODE_POINT);
                }
        };


        @Override
        protected void onDestroy() {
                super.onDestroy();
                EventBus.getDefault().unregister(this);
        }


        public static final int MAP_TYPE_SAVE_MAP_TASK = 2;

        private void sendMsg2Chest(String data) {
                String url = IpMsgConst.HTTP_URL_CHEST + "guideMapAction";
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("type", GuideMapAddTaskActivity.MAP_TYPE_SAVE_MAP_TASK + "");
                hashMap.put("data", data);
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                Log.e("TTS2Voice", result);
                                loadDialog.setCancelable(true);
                        }

                        @Override
                        public void onFailure() {
                                toastTools.showText("服务器异常！,请重试");
                                loadDialog.dismiss();
                                MapVoiceAndEyes.playMapVoiceAndEyes(MapVoiceAndEyes.voiceEyesList.get(8));
                        }
                });
        }

        private Dialog loadDialog;

        private void showLoadDialog() {
                if (loadDialog == null) {
                        loadDialog = new Dialog(this, R.style.MyDialogStyle);
                        loadDialog.setContentView(R.layout.guide_dialog_load);
                        ivOk = loadDialog.findViewById(R.id.guide_load_iv);
                        ivPb = loadDialog.findViewById(R.id.guide_load_pb);
                        tvLoad = (TextView) loadDialog.findViewById(R.id.guide_load_tv);
                }
                ivPb.setVisibility(View.VISIBLE);
                ivOk.setVisibility(View.INVISIBLE);
                tvLoad.setText("正在加载...");
                loadDialog.setCancelable(false);
                StatusBarUtil.hideVirtualKey(loadDialog);
                loadDialog.show();
        }


        class MyTaskAdapter extends RecyclerView.Adapter<MyHolder> {

                private final LayoutInflater layoutInflater;


                public List<MapPointInfo> getList() {
                        return list;
                }

                private final List<MapPointInfo> list;

                public MyTaskAdapter(Context context, List<MapPointInfo> list) {
                        this.layoutInflater = LayoutInflater.from(context);
                        this.list = list;
                }

                @NonNull
                @Override
                public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                        View inflate = layoutInflater.inflate(R.layout.guide_add_task_item, parent, false);
                        return new MyHolder(inflate, viewType);
                }

                @Override
                public void onBindViewHolder(@NonNull MyHolder holder, int position) {
                        if (getItemViewType(position) == 1) {
                                return;
                        }
                        MapPointInfo mapPointInfo = list.get(position);
                        holder.updateView(mapPointInfo, getItemViewType(position), position);
                }

                @Override
                public int getItemCount() {
                        return list.size();
                }

        }

        class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

                private TextView nameTv;

                private TextView indexTv;

                private Button moreButton;

                private int position;

                MyHolder(View itemView, int viewType) {
                        super(itemView);
                        indexTv = (TextView) itemView.findViewById(R.id.task_item_index_tv);
                        nameTv = (TextView) itemView.findViewById(R.id.task_item_name_tv);
                        moreButton = (Button) itemView.findViewById(R.id.task_item_more);
                        itemView.setOnLongClickListener(new View.OnLongClickListener() {
                                @Override
                                public boolean onLongClick(View v) {
                                        if (getItemViewType() == 1) {
                                                return false;
                                        }
                                        itemTouchHelper.startDrag(MyHolder.this);
                                        return false;
                                }
                        });
                        itemView.setOnClickListener(this);
                        moreButton.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                        showPopupWindow(v, position);
                                }
                        });
                }

                @Override
                public void onClick(View v) {
                        mPosition = position;
                        Intent intent = new Intent(GuideMapAddTaskActivity.this, GuideSetPointerActivity.class);
                        intent.putExtra("pointInfo", JSON.toJSONString(mTaskPointInfos.get(position)));
                        startForResultActivity(intent, REQ_CODE_POINT);
                }

                void updateView(MapPointInfo mapPointInfo, int itemViewType, int position) {
                        this.position = position;
                        int i = position + 1;
                        String format = String.format(Locale.getDefault(), "第%d步", i);
                        indexTv.setText(format);
                        nameTv.setText(mapPointInfo.getOtherName());
                }

        }

        private void showPopupWindow(View v, int position) {
                this.popPosition = position;
                if (popupWindow == null) {
                        View inflate = View.inflate(this, R.layout.guid_task_popup, null);
                        inflate.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                        popupWindow.dismiss();
                                        showDeleteDialog(popPosition);
                                }
                        });
                        popupWindow = new PopupWindow(inflate, (int) getResources().getDimension(R.dimen.px367), (int) getResources().getDimension(R.dimen.px108));
                        popupWindow.setOutsideTouchable(true);
                        popupWindow.setBackgroundDrawable(new ColorDrawable());
                }
                int[] location = new int[2];
                v.getLocationInWindow(location);
                int dimension = (int) getResources().getDimension(R.dimen.px367);
                int px34 = (int) getResources().getDimension(R.dimen.px34);
                popupWindow.showAtLocation(mainIv, Gravity.START | Gravity.TOP, location[0] - dimension, location[1] - px34);
        }


        class MyCallBack extends ItemTouchHelper.Callback {

                private MyTaskAdapter adapter;

                MyCallBack(MyTaskAdapter adapter) {
                        this.adapter = adapter;
                }

                @Override
                public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                        int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                        int swipeFlags = 0;
                        return makeMovementFlags(dragFlags, swipeFlags);
                }

                @Override
                public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                        if (target.getItemViewType() == 1) {
                                return true;
                        }
                        int adapterPosition = viewHolder.getAdapterPosition();
                        MapPointInfo remove = mTaskPointInfos.remove(adapterPosition);
                        mTaskPointInfos.add(target.getAdapterPosition(), remove);
                        adapter.notifyItemMoved(adapterPosition, target.getAdapterPosition());
                        return true;
                }

                /**
                 * 滑动删除
                 *
                 * @param viewHolder viewHolder
                 * @param direction  direction
                 */
                @Override
                public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                }

                /**
                 * 当拖拽结束的时候调用
                 *
                 * @param recyclerView recyclerView
                 * @param viewHolder   viewHolder
                 */
                @Override
                public void clearView(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                        super.clearView(recyclerView, viewHolder);
                        adapter.notifyDataSetChanged();
                }

        }


}
